package 算法.练习;

import java.util.concurrent.atomic.AtomicReference;

/**
 * @author:谢君臣
 * @Date:2021/6/22-11:32
 * @version:1.0
 * @function:
 */
public class SpinLock {
    private AtomicReference<Thread> atomicReference =new AtomicReference<>();
    public void lock(){
        while (!atomicReference.compareAndSet(null,Thread.currentThread()));
        System.out.println("lock successfully");
    }
    public void unlock(){
        atomicReference.compareAndSet(Thread.currentThread(),null);
        System.out.println("unlock successfully");
    }

    public static void main(String[] args) throws InterruptedException {
        SpinLock spinLock = new SpinLock();
        new Thread(() -> {
            spinLock.lock();
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("hahaha");
            spinLock.unlock();

        }).start();

        Thread.sleep(1);

        new Thread(() -> {
            spinLock.lock();
            System.out.println("hehehe");
            spinLock.unlock();
        }).start();

    }
}
